<!-- 合同-合同设置-合同续签意向表设置 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" showBack></PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20" :margin-top="20">
      <template #left>
        <a-input-search
          :style="{ width: '220px' }"
          placeholder="名称"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
          v-model="nameSearch"
        />
      </template>
      <template #right>
        <a-button type="primary" @click="add(null)">新增记录表</a-button>
        <a-button type="outline" @click="del(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <table-turn :table-data="getTableData" ref="tableRef" :args="args">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="name" title="记录表名称">
      </a-table-column>
      <a-table-column :width="200" data-index="remark" title="描述">
      </a-table-column>
      <a-table-column title="是否启用" data-index="enable" :width="150">
        <template #cell="{ record: { enable } }">
          <a-tag
            class="enable"
            :color="
              enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))',
              '--enable':
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))'
            }"
          >
            {{ enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="200"
        title="是否为默认模板"
        dataIndex="isShowDefault"
      >
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.isShowDefault"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column :width="200" data-index="" title="操作" fixed="right">
        <template #cell="{ record }">
          <a-tooltip content="预览">
            <icon-eye
              size="20"
              @click="goPreview(record.id)"
              style="
                padding-bottom: 3px;
                padding-right: 10px;
                color: #5085ff;
                cursor: pointer;
              "
            />
          </a-tooltip>
          <a-tooltip content="复制">
            <icon-copy
              size="18"
              style="
                padding-bottom: 3px;
                padding-right: 10px;
                color: #5085ff;
                cursor: pointer;
              "
              @click="goCopy(record.id)"
            />
          </a-tooltip>
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="goEdit(record.id)"
            />
          </a-tooltip>
          <a-tooltip content="删除" position="left">
            <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
              <icon-font
                type="icon-delete"
                :size="26"
                :style="{
                  cursor: 'pointer',
                  marginRight: '10px'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </table-turn>
  </ContentCard>
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
  <NoticeTemplate
    ref="templateRef"
    :data="currRecord.data"
    :add="addData"
    :business-type="businessType"
    :validateFun="validateName"
    :edit="EditData"
    :fn="tableRef"
    :title="`续签沟通表模板`"
  ></NoticeTemplate>
  <PreviewForm :data="currRecord.data" v-model:visible="previewFormVisible">
  </PreviewForm>
</template>

<script lang="ts" setup>
import {
  GetContractRenewalTemplateList,
  AddContractRenewalTemplate,
  PutContractRenewalTemplate,
  DelContractRenewalTemplate,
  CheckContractRenewalTemplate,
  GetContractRenewalTemplateDetail,
  ChangeContractRenewalTemplateDefault
} from '@/apis/management/contract/baseSetting';
import { cloneDeep } from 'lodash';
import { Message, Modal } from '@arco-design/web-vue';
import { validateRules } from '@/utils/common';
import { useSetupFormStore } from '@/store';

const router = useRouter();
const title = '合同续签意向表';
const store = useSetupFormStore();
let templateRef = ref();

// 表格配置
const args = {
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
};

let tableRef = ref();
let nameSearch = ref(''); // 搜索框值
// 储存当前数据
const currRecord: any = reactive({
  data: {}
});

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

let originData = ref(); // 储存原始数据
// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    const res = await GetContractRenewalTemplateList({
      name: nameSearch.value,
      ownerType: 1,
      ...pageData
    });
    originData.value = cloneDeep(res.content);
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

const businessType = ref([
  'SER_FUNC218F8148FCD249D2A3791D31B02669C0',
  'baseComponent'
]);
// 新增
const add = (record?: any) => {
  currRecord.data = {
    name: '',
    enable: 1,
    remark: ''
  };
  templateRef.value.fullScreen();
};

let previewFormVisible = ref(false);
const goPreview = async (id: number) => {
  try {
    const res: any = await GetContractRenewalTemplateDetail({ id });
    currRecord.data.name = res.name;
    currRecord.data.details = res.collectionModel;
    previewFormVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
};

let copyVisible = ref(false);
let currId = ref();
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

//  直接复制
const copyEmit = async (formData: any) => {
  try {
    const record: any = await GetContractRenewalTemplateDetail({
      id: currId.value
    });
    delete record.id;
    record.required = 2;
    record.name = formData.name;
    const template = cloneDeep(record);
    delete template.collectionModel;
    const templateId = await AddContractRenewalTemplate({
      level: 1, // 默认传1
      template: {
        ...template,
        ownerType: 1, // 默认传1
        isShowDefault: 2 // 复制的时候默认为不是默认模板
      }
    });
    const component = cloneDeep(record.collectionModel);
    for (let [index, item] of component.entries()) {
      delete item.id;
      const collection = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
      };
      const collectionId = await AddContractRenewalTemplate({
        level: 2, // 第二层默认传2
        collection
      });
      // 将返回的collectionId赋值给每一个控件
      item.controlModel.forEach((item2: any, index3: number) => {
        item2.collectionId = collectionId;
        delete item2.id;
      });
      await AddContractRenewalTemplate({
        level: 3, // 第三层传3
        control: item.controlModel
      });
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error) {
    console.log(error);
  }
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currRecord.data.name && currRecord.data.id) {
      //
    } else {
      const data = {
        name
      };
      const res = await validateRules(CheckContractRenewalTemplate, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 编辑 初始化控件数据
const goEdit = async (id: number, name?: string) => {
  const record: any = cloneDeep(await GetContractRenewalTemplateDetail({ id }));
  record.seconds = record.collectionModel;
  delete record.collectionModel;
  if (name) {
    record.name = name;
    delete record.id;
  }
  record.seconds.forEach((ele: any) => {
    if (name) delete ele.id;
    ele.componentList = ele.controlModel;
    delete ele.componentModel;
    ele.componentList.forEach((item: any) => {
      const { ctlCnName, ctlEnName, ctlComponentType, ctlCode, ctlFieldName } =
        item;
      item.uuid = ctlCode;
      item.componentName = ctlCnName;
      item.componentType = ctlComponentType;
      item.code = ctlCode;
      item.fieldName = ctlFieldName;
      item.enName = ctlEnName;
      if (name) delete item.id;
    });
  });
  currRecord.data = cloneDeep(record);
  templateRef.value.fullScreen();
};

// 新增 模板新增函数
const addData = async (data: any, componentList: any) => {
  try {
    // 第一层，返回templateId赋值给第二层子集
    const templateId = await AddContractRenewalTemplate({
      level: 1, // 默认传1
      template: {
        ...data,
        ownerType: 1 // 默认传1
      }
    });
    const component = cloneDeep(componentList);
    for (let [index, item] of component.entries()) {
      for (let item2 of item.componentList) {
        const collection = {
          cnName: item2.cnName,
          enName: item2.enName,
          subCode: item2.subCode,
          orderNo: item2.sort || index,
          templateId
        };
        const collectionId = await AddContractRenewalTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        // 将返回的collectionId赋值给每一个控件
        const control = item2.componentList.map((item2: any) => {
          item2.collectionId = collectionId;
          let data;
          if (item2.subsetControlRel) {
            data = {
              ...item2,
              ...item2.subsetControlRel
            };
          } else {
            data = {
              ...item2
            };
          }
          if (data.subsetControlRel) delete data.subsetControlRel;

          return data;
        });
        await AddContractRenewalTemplate({
          level: 3, // 第三层传3
          control
        });
      }
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};
// 新增 模板编辑函数
const EditData = async (data: any, componentList: any) => {
  try {
    const templateId = data.id;
    // 第一层，返回templateId赋值给第二层子集
    await PutContractRenewalTemplate({
      level: 1, // 默认传1
      template: {
        ...data,
        ownerType: 1 // 合同默认传1
      }
    });

    // 删除子集
    if (store.getCollectionsIds.length > 0) {
      await DelContractRenewalTemplate({
        type: 2, // 子集传2
        ids: store.getCollectionsIds
      });
      store.delCollectionsIds = [];
    }

    // 删除控件
    if (store.getControlIds.length > 0) {
      await DelContractRenewalTemplate({
        type: 3, // 控件传3
        ids: store.getControlIds
      });
      store.delControlIds = [];
    }

    const component = cloneDeep(componentList);
    // // 循环修改值的结构
    for (let [index, item] of component.entries()) {
      const collection: any = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
        // pid: item2.pid || 0
      };
      let collectionId = 0;
      if (item.id) {
        collection.id = item.id;
        await PutContractRenewalTemplate({
          level: 2, // 第二层默认传2
          funcTemplateType: 1, // 组织默认传1
          collection
        });
        collectionId = item.id;
      } else {
        collectionId = (await AddContractRenewalTemplate({
          level: 2, // 第二层默认传2
          collection
        })) as number;
      }
      for (let item2 of item.componentList) {
        item2.collectionId = collectionId;
      }
      await PutContractRenewalTemplate({
        level: 3, // 第三层传3
        funcTemplateType: 1, // 组织默认传1
        control: item.componentList
      });
    }

    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 搜索框搜索事件
const onSearch = () => {
  refresh();
};

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    // 获取更改状态之前的模板数据，并判断状态是否和当前的一样，如果一样则不能改成默认模板
    const temp = originData.value.find((item: any) => item.id === record.id);
    if (temp.isShowDefault === 1) Message.error('必须拥有一个默认模板！');
    else if (temp.enable !== 1)
      Message.error('不能将未启用的模板当作默认模板!');
    else
      await ChangeContractRenewalTemplateDefault({
        id: record.id
      });
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除数据
const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find(
                  (item: any) => item.isShowDefault === 1
                )
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelContractRenewalTemplate({
                  type: 1, // 模板传1
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                tableRef.value.loadData();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
      else {
        await DelContractRenewalTemplate({
          type: 1, // 模板传1
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        tableRef.value.loadData();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
